import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;

import DataType.MessageFormat;

class HeartBeat extends Thread {
	// responsible for receive message

	SocketSender sender;

	HeartBeat(SocketSender sender) {
		this.sender = sender;
	}

	public void closeSocket(Socket socket) {
		try {
			socket.close(); // close client socket
			System.out.println(Thread.currentThread().getName()
					+ " close socket !");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	ByteBuffer prepareHeartBeat(byte[] buffer) {
		byte[] data = new byte[18];
		System.arraycopy(buffer, 0, data, 0, 18);
		data[17] = (byte) ((data[17] + 1) % 128);
		ByteBuffer bb = ByteBuffer.wrap(data);
		bb.order(MessageFormat.byteOrder);
		return bb;
	}

	public void run() {
		byte[] buffer = new byte[1024];
		Socket socket = sender.getSocket();
		try {
			while (!this.isInterrupted()) {
				InputStream in = socket.getInputStream();
				int len = in.read(buffer);
				if ((len > 0) && (MessageFormat.isHeartBeatMessage(buffer))) {
					ByteBuffer bb = prepareHeartBeat(buffer);
					synchronized (sender.getBufferList()) {
						sender.getBufferList().add(bb);
					}
				} else {
					Thread.currentThread().interrupt();
				}
			}
		} catch (IOException e) {
			System.out.println("Socket other side is closed!");
			e.printStackTrace();
			sender.interrupt();
			closeSocket(socket);
		}
		System.out.println("HeartBeat Thread is interrupted!");
	}
}
